package tk.hongbo.server

import android.util.Log
import org.java_websocket.WebSocket
import org.java_websocket.handshake.ClientHandshake
import org.java_websocket.server.WebSocketServer
import java.net.InetSocketAddress
import java.nio.ByteBuffer


/**
 * Created by HongboZhao on 2022/1/11.
 */
const val TAG: String = "HChat"

class ServerSocket(private val serverManager: ServerManager, port: Int) :
    WebSocketServer(InetSocketAddress(port)) {

    override fun onOpen(conn: WebSocket?, handshake: ClientHandshake?) {
        Log.i(TAG, "Some one Connected...")
        serverManager.log("Socket连接打开")
    }

    override fun onClose(conn: WebSocket?, code: Int, reason: String?, remote: Boolean) {
        conn?.let { serverManager.UserLeave(it) }
        serverManager.log("断开连接")
    }

    override fun onMessage(conn: WebSocket?, message: ByteBuffer?) {
        serverManager.receiveBytes(message)
        serverManager.log("收到数据,${message?.remaining()} bytes")
    }

    override fun onMessage(conn: WebSocket?, message: String?) {
        serverManager.log("收到文本,${message}")
        if (message.equals("1")) {
            serverManager.SendMessageToUser(conn, "What?")
        }

        val result = message?.split(":")
        if (result?.size == 2) {
            if (result[0] == "user") {
                conn?.let { serverManager.UserLogin(result[1], it) }
            }
        }
    }

    override fun onError(conn: WebSocket?, ex: Exception?) {
        Log.i(TAG, "Socket Exception:" + ex.toString())
        serverManager.log("Socket连接错误${ex?.message}")
    }

    override fun onStart() {
        Log.i(TAG, "Socket Start")
        serverManager.log("Socket连接开始运行")
    }
}